//
//  LFPhotoBrowserController.swift
//  webApp
//
//  Created by Mical_LF on 2017/6/12.
//  Copyright © 2017年 Mical_LF. All rights reserved.
//

import UIKit
import SwiftyJSON
import Qiniu

private let reuseIdentifier = "LFCollectionViewCell"
private let logReuseIdentifier = "logReuseIdentifier"

class LFPhotoBrowserController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource, UIAlertViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var picCollectionView: UICollectionView?
    
    var logoCollectionView: UICollectionView?

    var bottomViewBG: UIView? = nil
    
    fileprivate var browser: LLPhotoBrowserViewController?

    var data: [UIImageView] = []
    var choiceImageArray: [Int] = []
    var choiceIndex: IndexPath? = nil
    var choiceLogoImage: UIImageView? = nil
    var logoImageJson: JSON? = nil
    var choiceBtn: UIButton? = nil;
    open var browserActionSheet: LLBrowserActionSheet?

    
    /// 1.0.1 图片数据源
    var bigUrlArray1_0_1: [Any?] = []
    var shareContent: String = ""
    var shareTitle: String = ""
    var signPicArray: [Any?] = [UIImage.init(named: "new_car"), UIImage.init(named: "presell"), UIImage.init(named: "recommend"), UIImage.init(named: "reserve"), UIImage.init(named: "sale-price"), UIImage.init(named: "Sold"), UIImage.init(named: "wholesale")]

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black

        //初始化底部视图
        self.initBottonView()
        //初始化相册视图
        self.initPicCollectionView()
        //初始化logo选择视图
        self.initLogoCollectionView()
        
        let leftBarBtn = UIBarButtonItem(image: UIImage(named: "title_icon_back_gray"), style: .done, target: self, action: #selector(backToPrevious))
        self.navigationItem.leftBarButtonItem = leftBarBtn
        
        let rightBarBtn = UIBarButtonItem(title: "发送", style: .plain, target: self,
                                         action: #selector(sendPic))
        self.navigationItem.rightBarButtonItem = rightBarBtn
        self.navigationController?.navigationBar.tintColor = UIColor.red
        
        //请求 获取logo 数据
        NetworkTools.requestData(.get, URLString: BaseUrl(a: "http://httpbin.org/get")) { (result) in
            let jsonStr  = "{\"companyId\":\"1234\",\"companyName\":\"新公司\",\"logoUrl\":\"https://f12.baidu.com/it/u=2874221126,594939198&fm=72\"}"
            let jsonData = jsonStr.data(using: String.Encoding.utf8, allowLossyConversion: false)
            self.logoImageJson = JSON(Data: jsonData!)
            print(self.logoImageJson!)
        }

    }
    
    //返回按钮点击响应
    func backToPrevious(){
        self.navigationController!.popViewController(animated: true)
    }
    
    //分享图片
    func sendPic(){
        let alertController = MyAlertController(title: self.shareTitle,
                                                message: self.shareContent,
                                                preferredStyle: .alert)
        let okAction = UIAlertAction(title: "复制", style: .default, handler: {
            action in
            
            //复制并分享
            UIPasteboard.general.string = self.shareContent 
            
            var shareImageArray: [Any] = [Any]()
            if self.choiceLogoImage != nil {
                //给相册加上相对应的lopgo图标
                for i in 0..<self.choiceImageArray.count {
                    let temIndexPath: Int = self.choiceImageArray[i]
                    var changeBaseImage: UIImage? = nil
                    let baseImage = self.bigUrlArray1_0_1[temIndexPath]
                    if baseImage is UIImage {
                        changeBaseImage = baseImage as? UIImage
                    }else if baseImage is String {
                        let imageView = UIImageView()
                        let url = URL(string: baseImage! as! String)
                        //先下载图片
                        imageView.kf.setImage(with: url)
                        changeBaseImage = imageView.image!
                        changeBaseImage = self.resizeImage(originalImg: changeBaseImage!)
                    }
                    
                    var logoImage = self.choiceLogoImage?.image
                    //设置logo 图片大小。
                    logoImage = logoImage?.newSizeImage(size: CGSize(width:300, height:300), source_image: logoImage!)
                    
                    //MARK: 这里是合成图片位置设置。显示图片的位置是XIB中固定的。修改约束即可
                    let resultImage = changeBaseImage?.imageWaterMarkPoint(str: "", strPoint: CGPoint(x:0,y:0), attri: [NSForegroundColorAttributeName: UIColor.red], image: logoImage, imagePoint: CGPoint(x:(changeBaseImage?.size.width)! - 300,y:(changeBaseImage?.size.height)! - 200), alpha: 1)
                    shareImageArray.append(resultImage!)
                }
            }else {
                //原图分享
                for i in 0..<self.choiceImageArray.count {
                    let temIndexPath: Int = self.choiceImageArray[i]
                    let baseImage = self.bigUrlArray1_0_1[temIndexPath]
                    if baseImage is UIImage {
                        shareImageArray.append(baseImage!)
                    }else if baseImage is String {
                        let imageView = UIImageView()
                        let url = URL(string: baseImage! as! String)
                        //先下载图片
                        imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                            
                        }, completionHandler: { (image, error, cacheType, imageURL) in
                            let shareImage = self.resizeImage(originalImg: image!)
                            shareImageArray.append(shareImage)
                        })
                    }
                }
            }
            if shareImageArray.count != 0 {
                self.shareMorePic(shareImageItem: shareImageArray)
            }
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
        
     }
    
    func shareMorePic(shareImageItem: [Any]) {

        //MARK: 打开分享
        let activityVC = UIActivityViewController.init(activityItems: shareImageItem as [Any], applicationActivities: nil)
        
        //全部写出来，是为了将用不到的图标去掉
        if #available(iOS 9.0, *) {
            activityVC.excludedActivityTypes = [UIActivityType.postToFacebook,UIActivityType.airDrop,UIActivityType.postToTwitter, UIActivityType.postToWeibo,UIActivityType.message,UIActivityType.mail,UIActivityType.print,UIActivityType.copyToPasteboard,UIActivityType.assignToContact,UIActivityType.saveToCameraRoll,UIActivityType.addToReadingList,UIActivityType.postToFlickr,UIActivityType.postToVimeo,UIActivityType.postToTencentWeibo,UIActivityType.airDrop,UIActivityType.openInIBooks]
        } else {
            activityVC.excludedActivityTypes = [UIActivityType.postToFacebook,UIActivityType.airDrop]
        }
        
        //分享回调
        activityVC.completionWithItemsHandler = {
            (activity, success, items, error) in
            print("Activity: \(String(describing: activity)) Success: \(success) Items: \(String(describing: items)) Error: \(String(describing: error))")
            //分享成功和失败
            if success == true {
//                let jsHandlerFunc = self.jsContext?.objectForKeyedSubscript("callAddThingCallbackExtern")
//                let dict = ["name": "分享成功了"] as [String : Any]
//                let _ = jsHandlerFunc?.call(withArguments: [dict])
                self.navigationController?.popViewController(animated: true)
            }else {
                
            }
        }
        
        //                        if (currentVC?.isKind(of: ViewController.self))! {
        self.present(activityVC, animated: true, completion: nil)
        //                        }

    }
    
    //MARK: botton
    func initBottonView() {
        bottomViewBG = UIView(frame: CGRect(x:0, y:0, width:0, height:0))
        self.view.addSubview(bottomViewBG!)
        bottomViewBG?.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
        }
        
        bottomViewBG?.backgroundColor = UIColor.gray
        
        let btnNameArray = ["添加标签", "添加LOGO", "添加图片"]
        for i: Int in 0...2 {
            let button:UIButton = UIButton(type:.system)
            button.frame = CGRect(x:(SCREEN_WIDTH / 3.0) * CGFloat(i), y:0, width:SCREEN_WIDTH/3.0, height:40)
            button.setTitle(btnNameArray[i], for:.normal)
            bottomViewBG?.addSubview(button)
            button.setTitleColor(UIColor.white, for: .normal)
            if i == 0 {
                button.setTitleColor(UIColor.red, for: .normal)
            }
            button.titleLabel?.font = UIFont.systemFont(ofSize: 13.0)
            button.tag = i + 100
            button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)
            choiceBtn = button
        }
    }
    
    func tapped(_ button:UIButton){
        if button.tag == 102 {
            browserActionSheet = LLBrowserActionSheet.init(titleArray: ["拍照", "从相册选择"], cancelTitle: "取消", didSelectedCell: { [] (index) in
                switch index {
                case 0:
                    self.openCamera()
                case 1:
                    self.openAlbum()
                default: break
                }
            })
            browserActionSheet?.show(self.view!)
        }else {
            for i: Int in 0...2 {
                let btn: UIButton = self.view.viewWithTag(i + 100) as! UIButton
                btn.setTitleColor(UIColor.white, for: .normal)
            }
            choiceIndex = nil
            choiceLogoImage = nil
            button.setTitleColor(UIColor.red, for: .normal)
            choiceBtn = button
            self.logoCollectionView?.reloadData()
            self.picCollectionView?.reloadData()
        }
    }
    
    //MARK: top
    func initPicCollectionView() {
        let layout = UICollectionViewFlowLayout()
        picCollectionView = UICollectionView(frame: CGRect(x:0, y:0, width:0, height:0), collectionViewLayout: layout)
        
        self.picCollectionView?.backgroundColor = UIColor.black
        self.view.addSubview(self.picCollectionView!)
        self.picCollectionView?.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
        }
        self.picCollectionView?.register(UINib.init(nibName: "LFPhotoBorwserCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier )
        
        self.picCollectionView?.delegate = self
        self.picCollectionView?.dataSource = self
        self.picCollectionView?.showsVerticalScrollIndicator = false
        self.picCollectionView?.showsHorizontalScrollIndicator = false
        
        layout.itemSize = CGSize(width: (SCREEN_WIDTH-40)/3.0, height: (SCREEN_WIDTH-40)/3.0 * (3/4.0))
    }
    
    //MARK: middle
    func initLogoCollectionView() {
        let layout = UICollectionViewFlowLayout()
        logoCollectionView = UICollectionView(frame: CGRect(x:0, y:0, width:0, height:0), collectionViewLayout: layout)
        
        self.logoCollectionView?.backgroundColor = UIColor.black
        self.view.addSubview(self.logoCollectionView!)
        self.logoCollectionView?.snp.makeConstraints { (make) in
            make.right.equalTo(self.view)
            make.left.equalTo(self.view)
            make.top.equalTo((self.picCollectionView?.snp.bottom)!).offset(20)
            make.height.equalTo((SCREEN_WIDTH-50)/4.0)
            make.bottom.equalTo((self.bottomViewBG?.snp.top)!).offset(-20)
        }
        self.logoCollectionView?.register(UINib.init(nibName: "LFLogoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: logReuseIdentifier )
        
        self.logoCollectionView?.delegate = self
        self.logoCollectionView?.dataSource = self
        self.logoCollectionView?.showsVerticalScrollIndicator = false
        self.logoCollectionView?.showsHorizontalScrollIndicator = false
        
        layout.itemSize = CGSize(width: ((SCREEN_WIDTH-50)/4.0), height: ((SCREEN_WIDTH-50)/4.0 - 20))
        layout.scrollDirection = .horizontal
    }

    // MARK: - collection Delegate & datasource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.picCollectionView == collectionView {
            return bigUrlArray1_0_1.count
        }else {
            if self.choiceBtn?.tag == 101 {
                if self.logoImageJson != nil {
                    return 1
                }
                return 0
            }else {
                return signPicArray.count
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //判断是图片还是logo  collectionView
        if self.picCollectionView == collectionView {
            let cell: LFPhotoBorwserCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LFPhotoBorwserCollectionViewCell
            
            let data = bigUrlArray1_0_1[indexPath.row]
            if data is UIImage {
                cell.bigImageView.image = data as? UIImage
            }else if data is String {
                cell.bigImageView.kf.setImage(with: URL.init(string: data as! String)!)
            }
            
            //-1 -- 代表未找到
            var currentIndex: Int = -1
            for index in 0..<choiceImageArray.count {
                let obj = choiceImageArray[index]
                if obj == indexPath.row {
                    currentIndex = index
                    break
                }
            }
            
            if currentIndex == -1 {
                cell.iconImageView.isHidden = true
                cell.logoImageView.image = nil;
            }else {
                cell.iconImageView.isHidden = false
                if choiceLogoImage != nil {
                    cell.logoImageView.image = choiceLogoImage?.image
                }else {
                    cell.logoImageView.image = nil
                }
            }
            return cell
        }else {
            let cell: LFLogoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: logReuseIdentifier, for: indexPath) as! LFLogoCollectionViewCell
            
            var data = signPicArray[indexPath.row]
            if self.choiceBtn?.tag == 101 {
                data = self.logoImageJson?["logoUrl"].string
            }
            if data is UIImage {
                cell.logoRealImage.image = data as? UIImage
            }else if data is String {
                cell.logoRealImage.kf.setImage(with: URL.init(string: data as! String)!)
            }
            
            if choiceIndex == indexPath {
                cell.layer.borderColor = UIColor.red.cgColor
                choiceLogoImage = cell.logoRealImage
            }else {
                cell.layer.borderColor = UIColor.gray.cgColor
            }
            
            return cell
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let isLogoView: Int
        if self.picCollectionView == collectionView {
            isLogoView = 0
        }else {
            isLogoView = 1
        }
        
        //判断是图片选择，还是logo选择
        switch isLogoView {
        case 0:
            
            data.removeAll()
            for index in 0..<bigUrlArray1_0_1.count {
                let cell: LFPhotoBorwserCollectionViewCell? = collectionView.cellForItem(at: IndexPath.init(row:index, section:0)) as? LFPhotoBorwserCollectionViewCell
                if let c = cell {
                    data.append((c.bigImageView)!)
                }
            }
            
            var currentIndex: Int = -1
            for index in 0..<choiceImageArray.count {
                let obj = choiceImageArray[index]
                if obj == indexPath.row {
                    currentIndex = index
                    break
                }
            }
            if currentIndex == -1 {
                if choiceImageArray.count >= 9 {
                    chrysan.show(.plain, message:"最大选中数量为9张图片", hideDelay: 1.5)
                    return ;
                }
                choiceImageArray.append(indexPath.row)
                self.title = "已选择\(choiceImageArray.count)张"
            }else {
                choiceImageArray.remove(at: currentIndex)
                self.title = "已选择\(choiceImageArray.count)张"
            }
            self.picCollectionView?.reloadData()
            
        default:
            //处理logo选中效果
            for index in 0..<bigUrlArray1_0_1.count {
                let cell: LFLogoCollectionViewCell? = collectionView.cellForItem(at: IndexPath.init(row:index, section:0)) as? LFLogoCollectionViewCell
                cell?.layer.borderColor = UIColor.gray.cgColor
                }
            let cell: LFLogoCollectionViewCell? = collectionView.cellForItem(at: indexPath) as? LFLogoCollectionViewCell
     
            if choiceIndex != indexPath {
                choiceIndex = indexPath as IndexPath
                cell?.layer.borderColor = UIColor.red.cgColor
            }else {
                choiceIndex = nil
                choiceLogoImage = nil
            }
            self.logoCollectionView?.reloadData()
            self.picCollectionView?.reloadData()
            
            break;
        }
    }
    
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        browser?.dismiss(animated: false, completion: { 
            
        })
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if self.picCollectionView == collectionView {
            return UIEdgeInsetsMake(10, 7.5, 10, 7.5)
        }else {
            return UIEdgeInsetsMake(10, 10, 10, 10)
        }
    }

    func reloadCollectionView() {
        choiceImageArray.removeAll()
        for index in 0..<bigUrlArray1_0_1.count {
            if index < 9 {
                choiceImageArray.append(index)
            }
        }
        self.title = "已选择\(choiceImageArray.count)张"
        self.picCollectionView?.reloadData()
        self.logoCollectionView?.reloadData()
    }
    
    //MARK:  调用系统相册获取图片方法
    func demoCameera(){
        openCamera()
        
    }
    func demoClicked(){
        openAlbum()
    }
    //打开相册
    func openAlbum(){
        //判断设置是否支持图片库
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //初始化图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //设置是否允许编辑
            //            picker.allowsEditing = editSwitch.on
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            print("读取相册错误")
        }
    }
    
    func openCamera(){
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            
            //创建图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //设置来源
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //允许编辑
            picker.allowsEditing = true
            //打开相机
            self.present(picker, animated: true, completion: { () -> Void in
                
            })
        }else{
            debugPrint("找不到相机")
        }
    }
    
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        //查看info对象
//        print(info)
        
        //显示的图片
        let image:UIImage!
        if picker.allowsEditing {
            //获取编辑后的图片
            image = info[UIImagePickerControllerEditedImage] as! UIImage
        }else{
            //获取选择的原图
            image = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        
        bigUrlArray1_0_1.append(image)
        self.picCollectionView?.reloadData()
        
        //上传图片
        let token = "4kfjaslkfdjaslkdfjasdkljjl"
        var data = UIImagePNGRepresentation(image)
        if data == nil {
            data = UIImageJPEGRepresentation(image, 1)
        }
        let upManager = QNUploadManager()
        upManager?.put(data, key: nil , token: token , complete: { (info, key, resp) -> Void in
            
            if (info?.statusCode == 200 && resp != nil){
                //上传完毕
                self.view.chrysan.show(.plain, message:"上传成功", hideDelay: 1.5)
                
            }else{
                //失败 
                self.view.chrysan.show(.plain, message:"上传失败", hideDelay: 1.5)

            }
            
        }, option: nil)
        
        //图片控制器退出
        picker.dismiss(animated: true, completion: {
            () -> Void in
        })
    }
    
    private func resizeImage(originalImg:UIImage) -> UIImage{
        
        //prepare constants
        let width = originalImg.size.width
        let height = originalImg.size.height
        let scale = width/height
        
        var sizeChange = CGSize()
        
        if width <= 1280 && height <= 1280{ //a，图片宽或者高均小于或等于1280时图片尺寸保持不变，不改变图片大小
            return originalImg
        }else if width > 1280 || height > 1280 {//b,宽或者高大于1280，但是图片宽度高度比小于或等于2，则将图片宽或者高取大的等比压缩至1280
            
            if scale <= 2 && scale >= 1 {
                let changedWidth:CGFloat = 1280
                let changedheight:CGFloat = changedWidth / scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
                
            }else if scale >= 0.5 && scale <= 1 {
                
                let changedheight:CGFloat = 1280
                let changedWidth:CGFloat = changedheight * scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
                
            }else if width > 1280 && height > 1280 {//宽以及高均大于1280，但是图片宽高比大于2时，则宽或者高取小的等比压缩至1280
                
                if scale > 2 {//高的值比较小
                    
                    let changedheight:CGFloat = 1280
                    let changedWidth:CGFloat = changedheight * scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                    
                }else if scale < 0.5{//宽的值比较小
                    
                    let changedWidth:CGFloat = 1280
                    let changedheight:CGFloat = changedWidth / scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                    
                }
            }else {//d, 宽或者高，只有一个大于1280，并且宽高比超过2，不改变图片大小
                return originalImg
            }
        }
        
        UIGraphicsBeginImageContext(sizeChange)
        
        //draw resized image on Context
        originalImg.draw(in: CGRect(x:0, y:0, width:sizeChange.width, height:sizeChange.height))
        
        //create UIImage
        let resizedImg = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return resizedImg!
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
